import * as THREE from 'three'
import createApp from '../../core'

function createSplineCurve (dom: HTMLElement) {
  const { camera, scene, gui } = createApp(dom)
  camera.position.set(0, 0, 100)
  camera.lookAt(scene.position)

  const axes = new THREE.AxesHelper(100)
  scene.add(axes)

  const { color } = data
  const pts = getPoints()
  const curve = new THREE.SplineCurve(pts)
  const points = curve.getPoints(50)
  const geometry = new THREE.BufferGeometry().setFromPoints(points)
  const material = new THREE.LineBasicMaterial({ color })
  const Spline = new THREE.Line(geometry, material)

  scene.add(Spline)

  function changeMesh () {
    const pts = getPoints()
    curve.points.forEach((pt, index) => {
      pt.copy(pts[index])
    })
    const points = curve.getPoints(50)
    geometry.setFromPoints(points)
  }

  const folder0 = gui.addFolder('第一个点')
  folder0.add(data.v0, 'x', -200, 200).onChange(changeMesh)
  folder0.add(data.v0, 'y', -200, 200).onChange(changeMesh)

  const folder1 = gui.addFolder('第二个点')
  folder1.add(data.v1, 'x', -200, 200).onChange(changeMesh)
  folder1.add(data.v1, 'y', -200, 200).onChange(changeMesh)

  const folder2 = gui.addFolder('第三个点')
  folder2.add(data.v2, 'x', -200, 200).onChange(changeMesh)
  folder2.add(data.v2, 'y', -200, 200).onChange(changeMesh)

  const folder3 = gui.addFolder('第四个点')
  folder3.add(data.v3, 'x', -200, 200).onChange(changeMesh)
  folder3.add(data.v3, 'y', -200, 200).onChange(changeMesh)

  const folder4 = gui.addFolder('第五个点')
  folder4.add(data.v4, 'x', -200, 200).onChange(changeMesh)
  folder4.add(data.v4, 'y', -200, 200).onChange(changeMesh)

  gui.addColor(data, 'color').onChange(() => {
    material.color = new THREE.Color(data.color)
  })
}

const data = {
  v0: { x: -100, y: 0 },
  v1: { x: -50, y: 50 },
  v2: { x: 0, y: 0 },
  v3: { x: 50, y: -50 },
  v4: { x: 100, y: 0 },
  color: 0xff0000
}
const p0 = new THREE.Vector2()
const p1 = new THREE.Vector2()
const p2 = new THREE.Vector2()
const p3 = new THREE.Vector2()
const p4 = new THREE.Vector2()

function getPoints () {
  const { v0, v1, v2, v3, v4 } = data
  p0.set(v0.x, v0.y)
  p1.set(v1.x, v1.y)
  p2.set(v2.x, v2.y)
  p3.set(v3.x, v3.y)
  p4.set(v4.x, v4.y)
  return [p0, p1, p2, p3, p4]
}

export {
  createSplineCurve
}
